class IssuesController < ApplicationController

  before_filter :login_required
  
  helper [:Issues, :Projects]

  protect_from_forgery :except => :change_developer_finish

  def index
    if params[:project_id] != nil
      @project = Project.find(params[:project_id])
      @issues = []
      if params[:issue_type] == "unassign"
        @project.issues.all.each do |i|
          if i.developer == []
            @issues << i
          end
        end
      else
        @issues = @project.issues.get_open_issues(params[:issue_type])
      end
    elsif params[:user_id] != nil
      @user = User.find(params[:user_id])
      if params[:issue_type] == "all"
        @issues = @user.assigned_issues.all(:joins => :project,
          :conditions => ["issues.state NOT IN (?)", ["resolved","finished"]],
          :order => 'projects.priority DESC, projects.should_be_finish_time ASC')
      else
        @issues = @user.assigned_issues.all(:joins => :project,
          :conditions => ["issues.priority = ? and issues.state NOT IN (?)", "#{params[:issue_type]}" , ["resolved", "finished"]],
          :order => 'projects.priority DESC, projects.should_be_finish_time ASC')
      end
    end
  end

  def new
    @issue = Issue.new
    @project = Project.find(params[:project_id])
  end

  def create
    @issue = Issue.new(params[:issue])
    @project = Project.find(params[:project_id])
    @issue.issueid = @project.current_issue_index
    @issue.users << current_user
    @issue.project_id = params[:project_id]
    @project.current_issue_index = @project.current_issue_index + 1

    if @project.save && @issue.save
      flash[:notice] = "创建Issue成功."
      result = 1
    else
      flash[:notice] = "创建Issue失败."
      result = nil
    end

    @units = Unit.new
    if @issue.id != nil
      @units = Unit.all(:conditions => ["user_id = ? and issue_id = ?", current_user.id ,@issue.id])
      if @units.size == 1
        @units[0].unit_role = "reporter"
        unless(@units[0].save)
          flash[:notice] << "  创建unit_role失败."
        else
          flash[:notice] << "  创建unit_role成功."
        end
      else
        flash[:notice] << "  创建unit_role成功."
      end
    end

    respond_to do |format|
      if result
        format.html { redirect_to(project_path(@project)) }
      else
        format.html { render :action => "new" }
      end
    end

  end

  def edit
    @issue = Issue.find(params[:id])
  end

  def update
    @issue = Issue.find(params[:id])

    respond_to do |format|
      if @issue.update_attributes(params[:issue])
        flash[:notice] = 'Issue was successfully updated.'
        format.html { redirect_to(@issue) }
      else
        format.html { render :action => "edit" }
      end

    end
  end

  def show
    @issue = Issue.find(params[:id])
    @tags = @issue.tester_tags
    @comment = @issue.logs.build
  end

  def change_state
    @issue = Issue.find(params[:id])
    @op_code = params[:op_code]
    
    @original_state = @issue.state
    
    if @issue.state == "assigned" || @issue.state == "reopen"
      @tags = @issue.project.tags.find_all_by_state("working")
      if @tags.empty?
        @released_tags = @issue.project.tags.find_all_by_state("released")
        if @released_tags.empty?
          #发生错误，请建立该项目的第一个版本标签
          redirect_to :back
          return
        else
          original_verno = @released_tags.last.name.scan(/\d+/).last
          new_verno = original_verno.to_i + 1
          new_verno = "0" * (original_verno.size - new_verno.to_s.size) + new_verno.to_s
          new_verno = @released_tags.last.name.gsub(original_verno, new_verno)
          @new_tag = Tag.new
          @new_tag.name = new_verno
          @new_tag.project = @issue.project
          @new_tag.save
          @new_tag.on_without_repeat(@issue)
        end
      else
        @tags.last.on_without_repeat(@issue)
      end
      
    end
    
    if @op_code.include?("working") || @op_code.include?("hang_up") || @op_code.include?("rework")
      eval "@issue.#{@op_code}"
    end

    if @op_code.include?("rework")
      url =  url_for :controller => 'issues', :action => 'show', :id => @issue
      MailingsWorker.asynch_send_mailing(:way => "reopen", :user_id => @issue.development.last.id, :issue_id => @issue.id, :url => url)
    end
    
    @log = Log.new
    @log.user_id = current_user.id
    @log.issue_id = @issue.id
    @log.log_type = "user"
    @log.content = "Issue的状态由 " + trans_issue_state_to_chs(@original_state) + " 转变成 " + trans_issue_state_to_chs(@issue.state)# + "  当前版本号为:" + @issue.tags.get_last_released_tag.name unless
    @log.content += ("，请在" + @issue.tags.last.name + "版本中验证") if @issue.state == "resolved"
    @log.save

    redirect_to :back
  end

  def change_developer
    @users = User.get_roles_users("developer", "pdm")
    @issue = Issue.find(params[:id])

    render :layout => false
  end

  def change_developer_finish
    @units = Unit.new
    @user = User.find(params[:user_id])
    @issue = Issue.find(params[:id])

    @log = Log.new
    @log.user_id = current_user.id
    @log.issue_id = @issue.id
    @log.log_type = "system"

    @units = Unit.all(:conditions => ["unit_role = ? and issue_id = ?", "developer", @issue.id])
    if @units.size > 1
      @units.each do |u|
        if @units.size > 1
          u.delete
        end
      end
    end
    
    if @units.size == 1
      @unit = @units[0]
      if @unit.user_id != @user.id
        @log.ex_issue_user_id = @unit.user_id
        @log.current_issue_user_id = @user.id

        @unit.user_id = @user.id

        if @unit.save && @log.save
          flash[:notice] = "  创建developer unit_role成功."
        else
          flash[:notice] = "  创建developer unit_role失败."
        end
      else
        flash[:notice] = "  所选user和之前一样，无需更新."
      end
    elsif @units.size == 0
      @log.ex_issue_user_id = 0
      @log.current_issue_user_id = @user.id

      @issue.users << @user
      @issue.save
      @log.save
      @units = Unit.all(:conditions => ["user_id = ? and issue_id = ?", @user.id, @issue.id])
      @units.each do |u|
        if u.unit_role == nil
          u.unit_role = "developer"
          if u.save
            @issue.assign
            flash[:notice] = "  创建developer unit_role成功."
          else
            flash[:notice] = "  创建developer unit_role失败."
          end
        end
      end
    end

    url =  url_for :controller => 'issues', :action => 'show', :id => @issue
    MailingsWorker.asynch_send_mailing(:way => "sent", :user_id => @user.id, :issue_id => @issue.id, :url => url)
    
    render :layout => false
  end
  
  private
  def trans_issue_state_to_chs(string)
    case string
    when "submitted"
      "未分配"
    when "assigned"
      "打开"
    when "resolved"
      "待测试"
    when "finished"
      "已关闭"
    when "reopen"
      "重新开启"
    when "suspend"
      "挂起"
    end
  end

end
